<?php
/**
 * Created by PhpStorm.
 * User: von
 * Date: 2017/11/17
 * Time: 18:24
 */
namespace backend\controllers;


use backend\models\AuthAssignment;
use backend\models\AuthItem;
use backend\models\InstationMessage;
use backend\models\PackageInitiationPlan;
use backend\models\User;
use backend\models\UserQuery;
use backend\models\UserSearch;
use common\models\Http;
use common\models\Package;
use common\models\PackageLog;
use common\models\Responses;
use common\models\UserModel;
use yii\db\Exception;
use yii\helpers\Json;
use yii\rest\ActiveController;
use yii\web\Controller;

class PackageInitiationPlanController extends BaseController
{
    const SET_PLAN_DATA          = 'package-initiation-plan/set-work-plan-data';
    const SET_TEAM_MEMBERS_DATA = 'package-initiation-plan/set-team-members-data';
    const DEL_WORK_PLAN_DATA    = 'package-initiation-plan/del-work-plan-data';

    public $enableCsrfValidation = false;
    public $layout = 'mypackageplan';
    public function optimistilock(){
        return 'var';
    }

    /*
     *  post 保存协同所有数据 Json
     *  @params : $teamMembersData (arry)[[id][负责人][预评估][尽调成员][其他说明]]团队成员信息
     *  @params : $workPlanData    (array)工作计划信息
     *  [
     *       //新增无id为0，更新获取id
     *      ['id'=>,'job'=>,'stage'=>],
     *      ['id'=>,'job'=>,'stage'=>]
     *  ]
     */
    public function actionSetPackageTeamWorkData(){
        echo header("Access-Control-Allow-Origin:*");
        if (\Yii::$app->request->isPost) {
            $teamMembersState['code'] = 300;
            $workPlanState['code'] = 300;

            $workPlanData = \Yii::$app->request->post('workPlanData', '');
            $teamMembersData = \Yii::$app->request->post('teamMembersData', '');
            //把工作人员进行分组
            $leader_name = !empty($teamMembersData['leaderArr'])?$teamMembersData['leaderArr']:'';
            $pre_evaluation_name = !empty($teamMembersData['yuArr'])?$teamMembersData['yuArr']:"";
            $due_diligence_name = !empty($teamMembersData['jinArr'])?$teamMembersData['jinArr']:'';
            $zongjian_name = !empty($teamMembersData['zongjianArr'])?$teamMembersData['zongjianArr']:'';
            //通过排列好的工作人员姓名 获取 工作人员的id,
            $teamMembersData['leader_id'] = PackageInitiationPlan::getUserId($leader_name,1);
            $teamMembersData['zongjian_id'] = PackageInitiationPlan::getUserId($zongjian_name,1);
            $teamMembersData['pre_evaluation_id'] = PackageInitiationPlan::getUserId($pre_evaluation_name,0);
            $teamMembersData['due_diligence_id'] = PackageInitiationPlan::getUserId($due_diligence_name,0);
            if (!empty($teamMembersData)&&!empty($workPlanData)){
                $teamMembersState = self::setPostTeamMembersData($teamMembersData,$workPlanData);
            }
            if (!empty($teamMembersData)&&empty($workPlanData)){
                $teamMembersState = self::setPostTeamMembersData($teamMembersData,json_encode([]));
            }
            if (json_decode($teamMembersState,true)['code']==200){
                $package_id         = !empty($teamMembersData['package_id'])?intval($teamMembersData['package_id']):0;

                //如果上传人和资产包负责人不相同--则更改access状态-----start---
                $packageModel = Package::findOne($package_id);
                if (!empty($packageModel)&&$packageModel->owner!=$teamMembersData['leader_id']){
                    $packageModel->access = 2;
                    $packageModel->save(false);
                }
                //如果上传人和资产包负责人不相同--则更改access状态-----end---

                //----编辑协同发送消息---------------------
                /*
                   *保存消息信息
                   */
                //根据package_id获取标题
                $pack_name = (new \yii\db\Query())->from(Package::tableName())->where(['=','id',$package_id])->one();
                //根据package_id获取状态
                $appStates  =  (new \yii\db\Query())->select('state')->from(Package::tableName())->where(['=','id',$package_id])->one();
                $appStateName = \Yii::$app->params['projectStatus'][$appStates['state']];//当前状态
                //最后一次更新人员
                $sender_id = \Yii::$app->user->getId();
                $userName = (new \Yii\db\Query())->from(User::tableName())->leftJoin('auth_item as ai','ai.name = user.department')->where(['=','id',$sender_id])->one();
                $message = [
                        'pack_name'=>$pack_name,
                        'appStates'=>$appStateName,
                        'lastUpdateUser'=>$userName['realname'],
                        'lastUpdateUserBumen'=>$userName['description'],
                ];
                //发送给关注此资产包的用户
                $user_id = (new \yii\db\Query())->from('package_like')->select('user_id')->where(['=','type',1])->andWhere(['=','package_id',$package_id])->all();
                $user_id = array_column($user_id,'user_id');
                if (!empty($user_id) && is_array($user_id)){
                    $data = [];
                    $data['sender'] = \Yii::$app->user->getId();//发件人id
                    $data['package_project_id'] = $package_id;//资产包id
                    $data['is_package'] = 1;//是否是资产包/1是资产包/2是项目
                    $data['message_val'] = json_encode($message); //消息内容 json

                    $data['user_id'] = $user_id;//收件人id
                    $data['message_state'] = \Yii::$app->params['UNREND'];//消息状态 0未阅读 1已阅读
                    $data['message_group'] = \Yii::$app->params['GUANZHU_UP']; //消息分类 1待审批提醒 2审批反馈 3关注更新*/

                    $param = [];
                    $param['where_sender'] = \Yii::$app->user->getId();//发件人id
                    $param['where_is_package'] = 1;//是否是资产包/1是资产包/2是项目
                    $param['where_package_project_id'] =  $package_id;//资产包id
                    $param['where_message_group'] =  \Yii::$app->params['GUANZHU_UP'];//资产包id 消息分类 1待审批提醒 2审批反馈 3关注更新
                    $param['is_guanzhu'] = 1; //如果是关注，则先删除message_user_group表的信息在添加
                    $savePackageMessage = \common\models\InstationMessage::saveMessage($param,$data);
                }else{
                    $savePackageMessage['code']=200;
                    $savePackageMessage['message']='保存协同成功,无关注用户,没发送消息';
                }
                //----编辑协同发送消息---------------------
                if (!empty($savePackageMessage) && $savePackageMessage['code']==200){
                    //保存log----fly--start---只保存成员，工作单独另保存---
                    $packageLog = new PackageLog();
                    $packageLog->package_id = $package_id;
                    $packageLog->created_at = date('Y-m-d H:i:s');
                    $packageLog->user_id = \Yii::$app->user->getId();
                    $notes = $teamMembersData['other_team_notes'];
                    $lname = !empty($leader_name[0])?$leader_name[0]:'';
                    $jiname = !empty($due_diligence_name[0])?$due_diligence_name[0]:' ';
                    $yuname = !empty($pre_evaluation_name[0])?$pre_evaluation_name[0]:' ';
                    $packageLog->log = "责任人->{$lname},预评估->{$jiname},尽调成员->{$yuname},工作内容->{$notes}";
                    $re = $packageLog->save();
                    if (!$re) {
                        throw new Exception('资产包日志保存失败');
                    }
                    //保存log----fly--end---只保存成员，工作单独另保存---
                    $savePackageMessage['message'] = '保存协同成功,发送消息成功';
                    return Json::encode(Responses::response200([],1,$savePackageMessage['message']));
                }else{
                    return Json::encode(Responses::response400('修改协同，发送消息失败'));
                }
                return Json::encode(Responses::response400('保存失败'));
            }
            return Json::encode(Responses::response400('保存失败'));
        }else{
            //获取用户信息
            $userID = \Yii::$app->user->id;         //用户id
            $userData = UserModel::find()->where(true)->asArray()->all();  //所有用户信息
            $userNameAndID = UserModel::find()->select('id,realname')->where(true)->asArray()->all();  //所有用户信息
            $userName =  UserModel::find()->where(['=','id',$userID])->asArray()->one();  //获取登陆用户信息
//          获取登陆用户的角色  先获取分配的权限
            $userRole = AuthAssignment::find()->where(['=','user_id',$userID])->asArray()->all();
            $RoleNameArr = [];
            foreach ($userRole as $k => $v) {
                array_push($RoleNameArr,$v['item_name']);
            }
//           在获取角色信息
            $userRoleName = AuthItem::find()->where(['or',['name'=>$RoleNameArr]])->asArray()->all();
            $RoleNameStr = '';
            foreach ($userRoleName as $k => $v){
                $RoleNameStr.= $v['description'].'-';
            }

            // 判断是否发起国协同
//            $packageplandata = self::actionGetpackageplan();
//            var_dump($packageplandata);die;
//            $RoleNameStr= mb_substr($RoleNameStr,0,mb_strlen($RoleNameStr)-1);
            $data['userData'] = $userData;
            $data['userNameAndID'] = $userNameAndID;

            $data['userName'] = $userName;
            $data['RoleNameStr'] = $RoleNameStr;

//            $data['initiationPlan'] = $packageplandata['data']['res']['initiationPlan'];
//            $data['workman'] = $packageplandata['data']['res']['workman'];
            return $this->render('save-package-team-work-data',$data);
        }
        return Json::encode(Responses::response400('保存失败'));
    }
    /*
        * post保存协同-团队成员信息
        */
    public static function setPostTeamMembersData($teamMembersData,$workPlanData){
        try{
            $params['teamMembersData'] = $teamMembersData;
            $params['workPlanData'] = $workPlanData;
            $SaveTeamMembersState = json_decode(self::actionSetTeamMembersData($params),true);
            if(!empty($SaveTeamMembersState) && $SaveTeamMembersState['code'] == 200) {
                return json_encode($SaveTeamMembersState);
            }
            return Json::encode(Responses::response400('保存失败'));
        }catch (\Exception $exception){
            return Json::encode(Responses::response400('保存失败'));
        }
    }
    public static function setPostTeamMembersDataAPI($params){
        $url = \Yii::$app->params['API_FRONT'] . self::SET_TEAM_MEMBERS_DATA;
        return Http::request($url,$params, 'POST');
    }
    /*
     *  @SWG\Post(
     *          path="/frontend/plan/saveplan",
     *          summary="保存协同信息",
     *          description="保存协同信息",
     *          @SWG\Parameter(
     *              name="package_id", description="资产包的id", required=true, type="int", default=0,db="package";
     *              name="pre_evaluation", description="预评估人员", required=true, type="text", default='',db="package_initiation";
     *              name="due_diligence", description="尽调成员", required=true, type="text", default='',db="package_initiation";
     *              name="owner", description="项目负责人", required=true, type="varchar(25)", default=0,db="package_initiation";
     *              name="other_team_notes", description="团队其它说明", required=true, type="text", default='',db="package_initiation";
     *          ),
     */
    public static function actionSetTeamMembersData($params)
    {
        $teamMembersData =  $params['teamMembersData'] ;
        $workPlanData    =  $params['workPlanData'] ;
        $id              = !empty($teamMembersData['id']) ? $teamMembersData['id'] : 0;
        $owner              = !empty($teamMembersData['leader_id']) ? preg_replace('# #', '',$teamMembersData['leader_id']) : '';
        $zongjian              = !empty($teamMembersData['zongjian_id']) ? preg_replace('# #', '',$teamMembersData['zongjian_id']) : '';
        $package_id         = !empty($teamMembersData['package_id'])?intval($teamMembersData['package_id']):0;
        $due_diligence      = !empty($teamMembersData['due_diligence_id']) ? preg_replace('# #', '', $teamMembersData['due_diligence_id']) : '';
        $pre_evaluation     = !empty($teamMembersData['pre_evaluation_id']) ? preg_replace('# #', '', $teamMembersData['pre_evaluation_id']) : '';
        $other_team_notes   = !empty($teamMembersData['other_team_notes']) ? preg_replace('# #', '', $teamMembersData['other_team_notes']) : '';
        $params = [
            'id'             => $id,
            'leader_id'             => $owner,
            'zongjian_id'             => $zongjian,
            'package_id'        => $package_id,
            'due_diligence_id'     => $due_diligence,
            'pre_evaluation_id'    =>$pre_evaluation,
            'other_team_notes' => $other_team_notes,
        ];
        $workPlanData = self::actionRegroup($workPlanData);
        $result = PackageInitiationPlan::setTeamMembersData($params,$workPlanData);
        if($result['code']==400) {
            return Json::encode(Responses::response404('提交失败'));
        }
        return Json::encode(Responses::response200([],1,'提交成功'));
    }

    /*
     *  post 获取此项目包是否发起过协同
     *  $package_id : 项目包id;
     *       @return  ：成功 [200,[99999,data]]
     *                ：失败 false
     */
    public static function actionGetPackagePlan($package_id)
    {
        //基本信息
        $data = self::actionGetpackageplanapidata($package_id);
//        var_dump(json_decode($data,true)['data']['res']);die;
        $userNameAndID = UserModel::find()->select('id,realname')->where(true)->asArray()->all();  //所有用户信息
        $dataC = json_decode($data,true)['data']['res'];
        $dataC['leader_name'] = !empty($dataC['workman']['leader_name'])?json_encode($dataC['workman']['leader_name']):json_encode('');
        $dataC['zongjian_name'] = !empty($dataC['workman']['zongjian_name'])?json_encode($dataC['workman']['zongjian_name']):json_encode('');
        $dataC['pre_evaluation_name'] = !empty($dataC['workman']['pre_evaluation_name'])?json_encode($dataC['workman']['pre_evaluation_name']):json_encode('');
        $dataC['due_diligence_name'] = !empty($dataC['workman']['due_diligence_name'])?json_encode($dataC['workman']['due_diligence_name']):json_encode('');
        $dataC['pre_evaluation_id'] = !empty($dataC['workman']['pre_evaluation_id'])?$dataC['workman']['pre_evaluation_id']:',';
        $dataC['leader_id'] = !empty($dataC['workman']['leader_id'])?$dataC['workman']['leader_id']:',';
        $dataC['zongjian_id'] = !empty($dataC['workman']['zongjian_id'])?$dataC['workman']['zongjian_id']:',';
        $dataC['due_diligence_id'] = !empty($dataC['workman']['due_diligence_id'])?$dataC['workman']['due_diligence_id']:',';

        $dataC['userNameAndID'] = $userNameAndID;
        if (!empty($package_id)){
            $ownerId = Package::find()->select('id,owner')->where(['=','id',$package_id])->asArray()->one();
            $dataC['ownerName']  = UserModel::find()->select('id,realname')->where(['=','id',$ownerId['owner']])->asArray()->one();
        }else{
            $dataC['ownerName']['realname']  = '';
            $dataC['ownerName']['id']  = '';
        }
        return $dataC;
    }

    /*
  *  post 获取此项目包是否发起过协同--显示在我的资产包页面
  *  $package_id : 项目包id;
  *       @return  ：成功 [200,[99999,data]]
  *                ：失败 false
  */
    public  function actionGetPackagePlan1()
    {
        $package_id = \Yii::$app->request->get('package_id',1);

        $result = \backend\controllers\DtActionFilter::checkPackage('package_initiation_plan',$package_id);
        if(!$result){
            if (Yii::$app->request->isAjax) {
                $response = Yii::$app->response;
                $response->format = \yii\web\Response::FORMAT_JSON;
                $response->data = ['status' => 'false','msg'=>Yii::t('yii', 'You are not allowed to perform this action.')];
                $response->send();
                exit;
            }else{
                throw new  \yii\web\ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
        }

        //基本信息
        $data = self::actionGetpackageplanapidata($package_id);
//        var_dump(json_decode($data,true)['data']['res']);die;
        $userNameAndID = UserModel::find()->select('id,realname')->where(true)->andWhere([ 'status'=> '1'])->asArray()->all();
        $zongjianName = UserModel::find()->select('id,realname')->where(['=','post','BranchManager'])->andWhere([ 'status'=> '1'])->asArray()->all();
//所有用户信息
        $dataC = json_decode($data,true)['data']['res'];
        $dataC['leader_name'] = !empty($dataC['workman']['leader_name'])?json_encode($dataC['workman']['leader_name']):json_encode('');
        $dataC['zongjian_name'] = !empty($dataC['workman']['zongjian_name'])?json_encode($dataC['workman']['zongjian_name']):json_encode('');
        $dataC['pre_evaluation_name'] = !empty($dataC['workman']['pre_evaluation_name'])?json_encode($dataC['workman']['pre_evaluation_name']):json_encode('');
        $dataC['due_diligence_name'] = !empty($dataC['workman']['due_diligence_name'])?json_encode($dataC['workman']['due_diligence_name']):json_encode('');
        $dataC['pre_evaluation_id'] = !empty($dataC['workman']['pre_evaluation_id'])?$dataC['workman']['pre_evaluation_id']:',';
        $dataC['leader_id'] = !empty($dataC['workman']['leader_id'])?$dataC['workman']['leader_id']:',';
        $dataC['zongjian_id'] = !empty($dataC['workman']['zongjian_id'])?$dataC['workman']['zongjian_id']:',';
        $dataC['due_diligence_id'] = !empty($dataC['workman']['due_diligence_id'])?$dataC['workman']['due_diligence_id']:',';

        $dataC['userNameAndID'] = $userNameAndID;
        $dataC['zongjianName'] = $zongjianName;
        if (!empty($package_id)){
            $ownerId = Package::find()->select('id,owner')->where(['=','id',$package_id])->asArray()->one();
            $dataC['ownerName']  = UserModel::find()->select('id,realname')->where(['=','id',$ownerId['owner']])->asArray()->one();
        }else{
            $dataC['ownerName']['realname']  = '';
            $dataC['ownerName']['id']  = '';
        }
        $dataC['package_id'] = $package_id;

        if (!isset($dataC['initiationPlan'])) {
            $dataC['initiationPlan'] = array();
        }
        return $this->render('save-package-team-work-data',$dataC);
    }
    /*
     *  @SWG\Post(
     *          path="/frontend/plan/saveplan",
     *          summary="判断是否发起协同",
     *          description="判断是否发起协同",
     *          @SWG\Parameter(
     *              name="package_id", description="资产包的id", required=true, type="int", default=0,db="package";
     *          )
     *         @return  ：成功 [200,[99999,data]]
     *                  ：失败 false
     */
    public static function actionGetPackagePlanApiData($package_id){
        $result = PackageInitiationPlan::getPackageState($package_id);
        return json_encode($result);
    }


    public function actionAjaxSetWorkPlan(){
//        $InitiationWorkPlanData = [
//            ['id'=>0,'stage'=>'tttttttt','job'=>'tttt','package_id'=>2],
//            ['id'=>0,'stage'=>'asdsad','job'=>'asddddddd','package_id'=>2],
//            ['id'=>1,'stage'=>'ffff','job'=>'fffff','package_id'=>2],
//            ['id'=>0,'stage'=>'asdsad','job'=>'rrrrrrrrr','package_id'=>2],
//            ['id'=>3,'stage'=>'rrrrrr','job'=>'rrrrrrrr','package_id'=>2],
//            ['id'=>0,'stage'=>'asdsad','job'=>'asddddddd','package_id'=>2],
//            ['id'=>0,'stage'=>'asdsad','job'=>'asddddddd','package_id'=>2],
//            ['id'=>5,'stage'=>'asd','job'=>'asd','package_id'=>2],
//            ['id'=>0,'stage'=>'asdsad','job'=>'asddddddd','package_id'=>2],
//        ];
//        var_dump(json_encode($InitiationWorkPlanData));die;
        if (!\Yii::$app->request->isAjax){
            $InitiationWorkPlanData = json_decode(\Yii::$app->request->post('plan',[]),true);
            if (empty($InitiationWorkPlanData)){
                return  false;
            }
            $WorkPlanState = self::setAjaxWorkPlanData($InitiationWorkPlanData);
            return Json::encode($WorkPlanState);
        }
    }
    /*
    * ajax保存协同-工作计划信息
    */
    public static function setAjaxWorkPlanData($params=[]){
        try{
            $SavePlanState = json_decode(self::setAjaxWorkPlanDataAPI($params),true);
            if(!empty($SavePlanState) && $SavePlanState['code'] == 200) {
                return $SavePlanState;
            }
            return Responses::response400('保存失败');
        }catch (\Exception $exception){
            return Responses::response400('保存失败');
        }
    }
    public static function setAjaxWorkPlanDataAPI($params){
        $url = \Yii::$app->params['API_FRONT'] . self::SET_PLAN_DATA;
        return Http::request($url,$params, 'POST');
    }
    /*
     *   *  @SWG\Post(
     *          path="/frontend/plan/saveplan",
     *          summary="保存协同--工作计划",
     *          description="保存协同--工作计划",
     *          @SWG\Parameter(
     *              name="package_id", description="资产包的id", required=true, type="int", default=0,db="package";
     *              name="job", description="结点", required=true, type="text", default='',db="package_initiation_plan";
     *              name="stage", description="阶段", required=true, type="varchar(25)", default=0,db="package_initiation_plan";
     *          ),
     */
    public function actionSetWorkPlanData(){
        $workplandata =  \Yii::$app->request->post();
        if (!empty($workplandata)){
            $data = self::actionRegroup($workplandata);
            $workPlanState = PackageInitiationPlan::setWorkPlanData($data['insertData'],$data['updateData']);
            return json_encode($workPlanState);
        }
        return json_encode(Responses::response400('保存失败'));
    }






    /*
        * ajax删除协同-工作计划
        * @$params: $id  array格式 json[1,2,3,4] ;
        */
    public function actionDelWorkPlan(){
        //&& !$_SESSION['realnameId']==''
//        $id = [1,2,3,4];
//        var_dump(json_encode($id));die;
        if (\Yii::$app->request->isAjax){
            $id = \Yii::$app->request->post('workId',0);
            if (empty($id)){
                return Json::encode([]);
            }
            $delState = self::delPostWorkPlanData($id);
            return Json::encode($delState);
        }
        return Json::encode(Responses::response400('删除失败'));
    }
    /*
     * del 删除协同-工作计划
     */
    public static function delPostWorkPlanData($params=''){
        try{
            $delWorkPlanState = json_decode(self::actionDelWorkPlanData($params),true);
            if(!empty($delWorkPlanState) && $delWorkPlanState['code'] == 200) {
                return $delWorkPlanState;
            }
            return Responses::response400('删除失败');
        }catch (\Exception $exception){
            return Responses::response400('删除失败');
        }
    }
    public static function delPostWorkPlanDataAPI($params){
        $url      = \Yii::$app->params['API_FRONT'].self::DEL_WORK_PLAN_DATA;
        return Http::request($url,$params, 'POST');
    }
    /*
     * 删除协同-工作计划
     */
    public static function actionDelWorkPlanData($delworkplandata){
        $delState = PackageInitiationPlan::delWorkPlanData($delworkplandata);
        return Json::encode($delState);
    }


    public static function actionRegroup($arrayData){
        $data=[];
        $insertData = [];
        $updateData = [];
        foreach ($arrayData as $k=>$v){
            if ($v['id']==0){
                $insertData[$k]['package_id'] = $v['package_id'];
                $insertData[$k]['stage'] = $v['stage'];
                $insertData[$k]['job'] = $v['job'];
            }else{
                $updateData[$k]['package_id'] = $v['package_id'];
                $updateData[$k]['stage'] = $v['stage'];
                $updateData[$k]['job'] = $v['job'];
                $updateData[$k]['id'] = $v['id'];
            }
        }
        $data=[
            'insertData'=>$insertData,
            'updateData'=>$updateData
        ];
        return $data;
    }
}
